package cn.kent.high.questions.timer;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 使用{@link java.util.concurrent.ScheduledThreadPoolExecutor#schedule(Runnable, long, TimeUnit)} 线程池
 * 这样干不会因为一个线程抛出异常导致其他任务全部终止
 * so开发中使用定时器功能，优先使用 ScheduledThreadPoolExecutor
 */
public class ScheduledThreadPoolExecutorTest {
    static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);

    public static void main(String[] args) {
        executor.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("--- one task ---");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                throw new RuntimeException("error");
            }
        }, 500, TimeUnit.MICROSECONDS);

        executor.schedule(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 2; i++) {
                    System.out.println("--- two task ---");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, 1000, TimeUnit.MICROSECONDS);

        executor.shutdown();
    }
}
